package api

import (
	"fmt"

	db "slgw_web/application/gormdb"

	models "openzbox.com/frame/echo/models/sl_gw01"

	"openzbox.com/frame/echo/response"

	utils "github.com/typa01/go-utils"
	"openzbox.com/frame/echo"
)

func Login(ctx echo.Context) error {
	username := ctx.FormValue("username")
	password := ctx.FormValue("password")
	//这里判断用户名密码的正确性
	if username != "" && password != "" {
		db := db.GetDB()
		user := models.User{}
		db.Where("UserName=?", username).Where("PassWord=?", password).Find(&user)
		if user.UserName != "" && user.PassWord != "" {
			tokenList := models.TokenList // 登录令牌的静态变量
			token := utils.GUID()
			if len(tokenList) > 0 {
				found := false
				for i := range tokenList {
					if tokenList[i].ID == user.ID {
						// 存在替换token
						tokenList[i].Token = token
						found = true
						break
					}
				}
				if !found {
					// 不存在匹配的令牌记录，新增一个
					data := models.AuthToken{
						ID:    user.ID,
						Token: token,
					}
					tokenList = append(tokenList, data)
				}
			} else {
				// 第一次登录
				data := models.AuthToken{
					ID:    user.ID,
					Token: token,
				}
				tokenList = append(tokenList, data)
			}
			models.TokenList = tokenList
			fmt.Println("models.TokenList", models.TokenList)
			return response.SuccessResult(token, ctx)
		} else {
			return response.FailResult(1, "账号或密码错误", ctx)
		}
	}

	return response.FailResult(1, "账号或密码必填", ctx)

}

// 获取账号
func GetUserName(ctx echo.Context) error {
	db := db.GetDB()
	User := models.User{}
	db.First(&User).Where("1=1")
	return response.SuccessResult(User.UserName, ctx)
}
func EditUserName(ctx echo.Context) error {
	username := ctx.FormValue("username")
	db := db.GetDB()
	db.Model(&models.User{}).Where("1=1").Update("UserName", username)
	return response.SuccessResult("修改成功", ctx)
}

func EditUserPassWord(ctx echo.Context) error {
	passWord := ctx.FormValue("passWord")
	oldpassWord := ctx.FormValue("oldpassWord")
	db := db.GetDB()
	user := models.User{}
	db.Where("PassWord = ?", oldpassWord).First(&user)
	if user.PassWord == "" {
		return response.FailResult(1, "旧密码不正确", ctx)
	}
	db.Model(&models.User{}).Where("1=1").Update("PassWord", passWord)
	return response.SuccessResult("修改成功", ctx)
}

// 初始化账号密码，慎用 隐藏接口
func InitUser(ctx echo.Context) error {
	db := db.GetDB()
	User := models.User{}
	db.First(&User).Where("1=1")
	if User.ID == 0 {
		db.Create(&models.User{
			UserName: "admin",
			PassWord: "admin",
		})
	} else {
		User.UserName = "admin"
		User.PassWord = "admin"
		db.Save(&User)

	}
	return response.SuccessResult("初始化后账号：admin，密码：admin", ctx)
}
